package bgate.hung.activity;

import java.util.ArrayList;
import java.util.Vector;
import bgate.connector.DataTransfer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import bgate.hung.workerclass.MenuAdapter;
import bgate.hung.workerclass.MenuItem;
import bgate.hung.workerclass.StaticBitmap;
import bgate.hung.workerclass.StaticData;

public class Login extends Activity {
	private static final String TAG = "LoginActivity";
	private static final int PROGRESSBAR_DIALOG = 1;

	private EditText accEditText, passEditText;
	private Button loginButton, rempassButton, menuButton;
	private ListView menuListView;
	private Toast toast = null;
	private String account = "", passWord = "";
	private DataTransfer dataTransfer = null;
	private IncommingMessage incommingMessage = null;
	private boolean loginBtPressed = false, isPushTask = false,
			connected = false, rememberPass = false;
	private ProgressDialog progressDialog;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		StaticBitmap.setResources(getResources(), this);
		DisplayMetrics mDisplay = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(mDisplay);
		StaticData.WIDTH = mDisplay.widthPixels;
		StaticData.HEIGHT = mDisplay.heightPixels;

		SharedPreferences sp = getSharedPreferences("CASINO_ONLINE", 0);
		account = sp.getString("ACCOUNT", "");
		passWord = sp.getString("PASSWORD", "");
		rememberPass = sp.getBoolean("REMEMBER_PASS", false);

		setContentView(R.layout.login_layout);
		accEditText = (EditText) findViewById(R.id.accountEditText_login_layout);
		passEditText = (EditText) findViewById(R.id.passwordEditText_login_layout);
		loginButton = (Button) findViewById(R.id.loginButton_login_layout);
		rempassButton = (Button) findViewById(R.id.rememberPassButton_login_layout);
		menuButton = (Button) findViewById(R.id.menuButton_login_layout);
		menuListView = (ListView) findViewById(R.id.menuListView_login_layout);

		progressDialog = new ProgressDialog(Login.this);
		progressDialog.setMessage("Xin chờ ...");

		accEditText.setText(account);
		passEditText.setText(passWord);
		if (rememberPass)
			rempassButton.setBackgroundResource(R.drawable.remember_button_on);
		MenuAdapter adapter = new MenuAdapter(getBaseContext(),
				R.layout.menu_listview_item, getInitMenu());
		menuListView.setAdapter(adapter);
		menuListView.setVisibility(View.INVISIBLE);

		loginButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!loginBtPressed) {
					account = accEditText.getText().toString();
					passWord = passEditText.getText().toString();
					if (account.length() >= 6 && passWord.length() >= 6) {
						loginBtPressed = true;
						new ConnectionTask().execute();
					} else {
						toast = Toast.makeText(Login.this,
								"Tên hoặc mật khẩu dài ít nhất 6 ký tự",
								Toast.LENGTH_SHORT);
						toast.show();
					}
				}
			}
		});

		rempassButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (rememberPass) {
					rememberPass = false;
					rempassButton
							.setBackgroundResource(R.drawable.remember_button_off);
				} else {
					rememberPass = true;
					rempassButton
							.setBackgroundResource(R.drawable.remember_button_on);
				}
			}
		});

		menuButton.setOnClickListener(new View.OnClickListener() {
			private boolean mGoOut;

			public void onClick(View v) {

				mGoOut = !mGoOut;
				Log.d("onclick", "click");
				if (mGoOut) {
					Animation slideOut = AnimationUtils.loadAnimation(
							Login.this, R.anim.slide_out);
					menuListView.setAnimation(slideOut);
					slideOut.setAnimationListener(new AnimationListener() {

						public void onAnimationStart(Animation animation) {
							// lv.setVisibility(View.VISIBLE);

						}

						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						public void onAnimationEnd(Animation animation) {
							menuListView.setVisibility(View.VISIBLE);

						}
					});
					Log.d("click", "in");

				} else {
					Animation slideIn = AnimationUtils.loadAnimation(
							Login.this, R.anim.slide);
					menuListView.setAnimation(slideIn);
					slideIn.setAnimationListener(new AnimationListener() {

						public void onAnimationStart(Animation animation) {
							// TODO Auto-generated method stub

						}

						public void onAnimationRepeat(Animation animation) {
							// TODO Auto-generated method stub

						}

						public void onAnimationEnd(Animation animation) {

							menuListView.setVisibility(View.INVISIBLE);
						}
					});
					// lv.setAnimation(slideOut);

					Log.d("click", "out");
				}

				if (mGoOut)
					menuButton
							.setBackgroundResource(R.drawable.menu_button_close);
				else
					menuButton
							.setBackgroundResource(R.drawable.menu_button_open);
			}
		});

		menuListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (position == 0) {
					enterRegister();
				}
			}
		});
	}

	public Dialog onCreateDialog(int id) {
		LayoutInflater factory = LayoutInflater.from(this);

		return null;
	}

	public void onResume() {
		super.onResume();
		dataTransfer = DataTransfer.getInstance();
		if (incommingMessage == null)
			incommingMessage = new IncommingMessage(dataTransfer.getOutQueue());
		if (!isPushTask && incommingMessage != null) {
			dataTransfer.putTask(incommingMessage);
			isPushTask = true;
		}
	}

	public void onPause() {
		super.onPause();
		if (isPushTask) {
			dataTransfer.removeTask(incommingMessage);
			isPushTask = false;
		}
		incommingMessage = null;
		if (toast != null)
			toast.cancel();
		Log.d(TAG, "LoginActivity onPause");
	}

	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "LoginActivity onDestroy");
	}

	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Thoát chương trình ?")
				.setCancelable(false)
				.setPositiveButton("Có", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						SharedPreferences sp = getSharedPreferences(
								"CASINO_ONLINE", 0);
						SharedPreferences.Editor editor = sp.edit();
						if (rememberPass && !account.equals("")
								&& !passWord.equals("")) {
							editor.putString("ACCOUNT", account);
							editor.putString("PASSWORD", passWord);
							editor.putBoolean("REMEMBER_PASS", true);
							editor.commit();
						} else {
							editor.putString("ACCOUNT", "");
							editor.putString("PASSWORD", "");
							editor.putBoolean("REMEMBER_PASS", false);
							editor.commit();
						}
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				})
				.setNegativeButton("Không",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private ArrayList<MenuItem> getInitMenu() {
		ArrayList<MenuItem> menu = new ArrayList<MenuItem>();
		MenuItem item1 = new MenuItem(StaticBitmap.getRegisterMenuItemImage(),
				"Đăng ký");
		menu.add(item1);
		MenuItem item2 = new MenuItem(StaticBitmap.getLosePassMenuItemImage(),
				"Quên mật khẩu");
		menu.add(item2);
		MenuItem item3 = new MenuItem(StaticBitmap.getEnMenuItemImage(),
				"Tiếng Anh");
		menu.add(item3);
		MenuItem item4 = new MenuItem(
				StaticBitmap.getIntroductionMenuItemImage(), "Hướng dẫn");
		menu.add(item4);
		MenuItem item5 = new MenuItem(
				StaticBitmap.getCallSupportMenuItemImage(), "Gọi trợ giúp");
		menu.add(item5);
		return menu;
	}

	private class ConnectionTask extends AsyncTask<Void, Boolean, Boolean> {

		public void onPreExecute() {
			progressDialog.show();
		}

		public void onPostExecute(Boolean result) {
			logIn(result);
		}

		@Override
		public Boolean doInBackground(Void... a) {
			// TODO Auto-generated method stub
			dataTransfer = DataTransfer.getInstance();

			// Connect server
			if (incommingMessage == null)
				incommingMessage = new IncommingMessage(
						dataTransfer.getOutQueue());
			if (!connected)
				connected = dataTransfer.connect();
			if (connected && !isPushTask && incommingMessage != null) {
				dataTransfer.putTask(incommingMessage);
				isPushTask = true;
			}
			return connected;
		}
	}

	private void logIn(boolean result) {
		loginBtPressed = false;
		if (result) {
			// Send request
			Log.d(TAG, "Connect successful!");
			dataTransfer.requestData("}LO|" + account + "|" + passWord + "&");
		} else {
			disconnectMessageHandler.sendEmptyMessage(0);
			Log.d(TAG, "Connect fail!");
		}
	}

	final Handler wrongMessageHandler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.cancel();
			toast = Toast.makeText(Login.this,
					"Bạn nhập sai mật khẩu hoặc tài khoản chưa tồn tại!",
					Toast.LENGTH_LONG);
			toast.show();
		}
	};

	final Handler disconnectMessageHandler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.cancel();
			toast = Toast.makeText(Login.this, "Không thể kết nối đến server",
					Toast.LENGTH_SHORT);
			toast.show();
		}
	};

	private void enterChoiseGame() {
		Intent intent = new Intent(this, ChoiseGame.class);
		intent.putExtra("ACCOUNT", account);
		progressDialog.cancel();
		startActivity(intent);
	}

	private void enterRegister() {
		Intent intent = new Intent(this, Register.class);
		startActivity(intent);
	}

	private class IncommingMessage implements Runnable {
		private final Vector mInQueue;

		public IncommingMessage(Vector inQueue) {
			this.mInQueue = inQueue;
		}

		public void run() {

			try {
				Thread.sleep(10);
				if (mInQueue.size() > 0) {

					String data = (String) mInQueue.elementAt(0);
					mInQueue.removeElementAt(0);
					Log.d(TAG, data);
					Vector<String> tempResultData = splitString(data, '}');
					for (int k = 0; k < tempResultData.size(); k++) {
						Vector<String> resultData = splitString(
								tempResultData.elementAt(k), '|');
						for (int i = 0; i < resultData.size(); i++) {
							String s = resultData.elementAt(i);
							if (s.equals("LO")) {
								s = resultData.elementAt(i + 1);
								if (s.equals("0")) {
									wrongMessageHandler.sendEmptyMessage(1);
									break;
								} else if (s.equals("1")) {
									enterChoiseGame();
									break;
								}
							}

							// if (s.equals("MSG")) {
							// s = resultData.elementAt(i + 1);
							// String sender = s;
							// s = resultData.elementAt(i + 2);
							// String content = s;
							// setMessageBox(sender, content);
							// }
						}
					}
				}
			} catch (InterruptedException ex) {
				Log.d(TAG, ex.toString());
			} catch (NullPointerException ex) {
				Log.d(TAG, ex.toString());
			}

		}

	}

	private Vector<String> splitString(String string, char delimiter) {
		Vector<String> mResult = new Vector<String>();
		TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(
				delimiter);

		// Once per string to split
		splitter.setString(string);
		for (String s : splitter) {
			String temp = "";
			for (int i = 0; i < s.length(); i++) {
				if (s.charAt(i) != '}' && s.charAt(i) != '&')
					temp += s.charAt(i);
			}
			mResult.addElement(temp);
		}

		return mResult;
	}
}